package com.qf.controller;

import com.qf.doamin.SystemAdmin;
import com.qf.entity.BusinessException;
import com.qf.entity.ResultEntity;
import com.qf.service.IUserService;
import com.qf.utils.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Set;

@Controller
public class CommonController {

    @Autowired
    private IUserService userService;

    @RequestMapping(value = "/login")
    @ResponseBody
    public ResultEntity login(String username, String password, HttpSession session){ // 123456

        // 先根据用户名查询对象
        SystemAdmin systemAdmin = userService.login(username);

        if(systemAdmin == null){
            throw new BusinessException(2000,"用户名不存在");
        }

        // 密码的比对
        if(!systemAdmin.getPassword().equals(password)){

            throw new BusinessException(2001,"用户名获密码错误");
        }

        // 查询用户的权限
        Set<String> perSet = userService.getPerSetByUserId(systemAdmin.getId());
        systemAdmin.setPerSet(perSet);

        systemAdmin.setPassword(null); // 把放到session中的用户名密码设置为null

        // 把当前登录的用户放入到session中
        session.setAttribute(Constants.SESSION_USER,systemAdmin);

        return ResultEntity.success("toIndex");
    }
}
